<template>
  <div class="">
    <!-- 搜索 -->
    <SearchBlock ref="searchBlockRef" @clickQuery="clickQuery" @clickAdd="clickAdd" />

    <hz-table ref="tableRef" :tableConfig="tableConfig" :columnSelection='false' :pagination="false">
      <template #action="{ column, record, text, index }">
        <el-button type="primary" size="small" link @click="clickEdit(record)">编辑</el-button>
      </template>
    </hz-table>

    <!-- 详情 -->
    <hz-dialog v-model="dialog.show" :title="dialog.title">
      <add-edit :formConfig="formConfig" :idsToNamesForAll="idsToNamesForAll" :allSiteList="allSiteList" ></add-edit>
    </hz-dialog>
  </div>
</template>
<script setup>
import { ref, onMounted, reactive, computed, getCurrentInstance } from "vue";
import SearchBlock from "./cpSearchBlock.vue";
import AddEdit from "./cpAddEdit.vue";
import { useStore } from "vuex";

const { proxy } = getCurrentInstance();
const { moment } = proxy.$util
const store = useStore();
const searchBlockRef = ref(null);
const tableRef = ref(null);

const tableConfig = reactive({
  columns: [
    { label: "优惠券名称", prop: "couponName", 'width': 180, showTooltip: false },
    { label: "承担费用", prop: "couponFeeOwner_label", 'width': 100, },
    { label: "面值/元", prop: "couponValue_label", 'width': 100, },
    { label: "截止有效期", prop: "expiredAt_label", 'width': 180, },
    // { label: "面值", prop: "couponValue", 'width': 500, showTooltip: false }, 
    { label: "适用区域", prop: "areaListStr", 'min-width': 200, showTooltip: false },
    { label: "适用站点", prop: "siteListStr", 'min-width': 200, showTooltip: false },
    { label: "适用店铺", prop: "storeListStr", 'min-width': 200, showTooltip: false },
    { label: "操作", prop: "action", 'width': 80, scopeVal: true, fixed: 'right' },
  ],
  dataSource: [],
  // pageNo: 1,
  // pageSize: 10,
  // total: 0,
});
const dialog = reactive({
  show: false,
})
const formConfig = reactive({
  dataObj: {},
  type: 'add',
  dialog: dialog,
  okCallback: clickQuery,
})

const allStoreList = ref([])
const allSiteList = ref([])
const allAreaList = computed(() => {
  return store.state.areaOption
})

onMounted(() => {
  clickQuery();
})

// 点击查询
function clickQuery(data) {
  /* if (!data) {
    searchBlockRef.value.clickQuery();
    return;
  }
  let { pageSize, pageNo, total } = tableConfig
  let param = { ...data, pageSize, pageNo, total }; */

  proxy.$http.get('/jx/jxMarketing/queryAllCoupons').then(res => {
    if (res.code == 200) {
      tableConfig.dataSource = Array.isArray(res.result) ? res.result : [];
      tableConfig.dataSource.forEach(val => {
        try {
          val.couponFeeOwner_label = val.couponFeeOwner[0] == 'platform' ? '平台' : '店铺'
          val.couponValue_label = val.couponValue / 100;
          val.expiredAt_label = moment(val.expiredAt).format('YYYY-MM-DD HH:mm:ss');
          // val.siteIds = ['1739843926620872705', '1740554934708580353']  // 测试
        } catch (error) {
          console.log(error);
        }
      })
      handleAreaData();
      handleSiteAndStore();
      // tableConfig.total = res.result.totalCount
    } else {
      // tableConfig.total = 0;
    }
  })
}

// 适用站点及店铺的数据转化
function handleSiteAndStore() {
  let params = {
    pageNo: 1,
    pageSize: 10000,
    keyword: '',
  }

  // 站点
  proxy.$http.get('/jx/jxSiteManage/querySitesByRegionOrKeyword', { params }).then(res => {
    if (res.code != 200) {
      return;
    }
    allSiteList.value = res.result.sites || [];
    tableConfig.dataSource.forEach(coupon => {
      coupon.siteListStr = idsToNamesForAll('site', coupon.siteIds)
    })
  })

  // 店铺
  proxy.$http.get('/jx/jxStoreManage/queryStoreByKeyword', { params }).then(res => {
    if (res.code != 200) {
      return
    }
    allStoreList.value = res.result.stores || [];
    tableConfig.dataSource.forEach(coupon => {
      coupon.storeListStr = idsToNamesForAll('store', coupon.storeIds)
    })
  })
}

// 从ids转成要显示的名称字符串，适用于区域、站点、店铺。
// ids:要装化的id;dataSource:转化数据源；idAttr:数据项的id属性名;nameAttr:数据项的name属性名
function idsToNames(ids, dataSource = [], idAttr = '', nameAttr = '') {
  let resultStr = ''
  let list = ids || [];
  
  if (list.length == 1 && list[0] == '*') {
    return '全部'
  } 
  
  list.forEach(id => {
    let obj = dataSource.find(item => item[idAttr] == id)
    if (obj) {
      resultStr += '，' + obj[nameAttr]
    }
  })
  
  return resultStr.replace('，', '');
}

// 转化区域、站点、店铺
function idsToNamesForAll(type, ids) {
  let resultStr = '';
  if (type == 'eara') {
    resultStr = idsToNames(ids, store.state.areaOption, 'id', 'name')
  } else if (type == 'store') {
    resultStr = idsToNames(ids, allStoreList.value, 'id', 'storeName')
  } else if (type == 'site') {
    resultStr = idsToNames(ids, allSiteList.value, 'siteId', 'siteName')
  }
  return resultStr
}

// 转化区域数据
function handleAreaData() {
  let param = {
    forceUpdate: false, okCallback: (areaList) => {
      console.log('areaList', areaList)
      tableConfig.dataSource.forEach(coupon => {
        coupon.areaListStr = idsToNamesForAll('eara', coupon.regionIds)
      })
    }
  }
  store.dispatch('getAreaOptionData', param)
}

// 新增优惠券
function clickAdd() {
  let obj = {
    // couponId: 'aaaa',   //  优惠券id，创建新优惠券时，不需要此字段；编辑优惠券时，需要此字段
    couponName: '新的优惠券',   //  优惠券名称，会在小程序上显示，比如 “新手大礼包”，“1元券”，“2元券”
    couponValue: '100',   //  券金额，比如1元，2元等
    amountPerUser: '1',   //  每个用户可以领取几张，比如，新手大礼包，用户可以领取多张 1元或2元券；其他券，通常情况下，每个用户每天只能领取一张
    expiredAt: moment().add(7, 'days').toDate().getTime(),   //  有效期截止时间
    regionIds: ['*'],   //  * 号表示所有区域，多个区域id之间使用逗号分隔
    siteIds: ['*'],   //  * 号表示所有站点，多个站点id之间使用逗号分隔
    storeIds: ['*'],   //  * 号表示所有店铺，多个店铺id之间使用逗号分隔
    couponFeeOwner: ['platform', 100],   //  有谁来承担优惠券对应的费用，以及承担金额 ["platform": 150]，金额单位为分，当前取值只有2个，platform 和 merchant
  }
  console.log(obj);
  formConfig.dataObj = obj;
  dialog.show = true;
  dialog.title = '创建优惠券';
}

// 点击编辑按钮
function clickEdit(record) {
  dialog.show = true;
  dialog.title = '编辑优惠券';
  formConfig.type = 'edit';
  formConfig.dataObj = { ...record };
}

</script>
<style lang="scss" scoped></style>
